package logic

import (
	"context"
	"database/sql"
	"fmt"
	"time"

	"paper-pro/app/usercenter/model"
	"paper-pro/app/usercenter/rpc/internal/svc"
	"paper-pro/app/usercenter/rpc/pb"
	"paper-pro/app/usercenter/rpc/usercenter"
	"paper-pro/pkg/tool"
	"paper-pro/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

var ErrUserAlreadyRegisterError = xerr.NewErrMsg("用户名已使用")

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) registerParamCheck(in *pb.RegisterReq) error {
	if len(in.Nickname) == 0 {
		return errors.Wrap(xerr.ErrRpcReqParam, "Register nickname is empty")
	}
	user, err := l.svcCtx.UserModel.FindOneByNickname(l.ctx, in.Nickname)
	if err != nil && err != model.ErrNotFound {
		return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "nickname:%s, err:%V", in.Nickname, err)
	}
	if user != nil {
		return errors.Wrapf(ErrUserAlreadyRegisterError, "Register user exists nickname:%s, err:%V",
			in.Nickname, err)
	}
	return nil
}

func (l *RegisterLogic) registerNewUser(in *pb.RegisterReq) (sql.Result, error) {
	user := new(model.User)
	user.Nickname = in.Nickname
	if len(in.Password) == 0 {
		return nil, errors.Wrap(xerr.ErrRpcReqParam, "Register password is empty")
	}
	md5Password, err := tool.Md5ByString(in.Password)
	if err != nil {
		return nil, err
	}
	user.Password = md5Password
	user.Email = in.Email
	user.LastLoginTime = time.Now()
	insertRes, err := l.svcCtx.UserModel.Insert(l.ctx, user)
	if err != nil {
		return nil, fmt.Errorf("DB insert error: %w", err)
	}
	return insertRes, err
}

func (l *RegisterLogic) Register(in *pb.RegisterReq) (*pb.RegisterResp, error) {

	if err := l.registerParamCheck(in); err != nil {
		return nil, errors.Wrap(err, "Register failed: Check param error")
	}

	insertRes, err := l.registerNewUser(in)
	if err != nil {
		return nil, fmt.Errorf("Register failed: Create new User error: %w", err)
	}

	userId, err := insertRes.LastInsertId()
	if err != nil {
		return nil, fmt.Errorf("Register generate token failed: DB User insertRes.LastInsertId error: %w", err)
	}
	generateTokenLogic := NewGenerateTokenLogic(l.ctx, l.svcCtx)
	tokenResp, err := generateTokenLogic.GenerateToken(&usercenter.GenerateTokenReq{
		UserId: userId,
	})
	if err != nil {
		return nil, errors.Wrapf(ErrGenerateTokenError, "GenerateToken userId: %d", userId)
	}

	return &pb.RegisterResp{
		AccessToken:  tokenResp.AccessToken,
		AccessExpire: tokenResp.AccessExpire,
		RefreshAfter: tokenResp.RefreshAfter,
	}, nil
}
